import React, { useState, useEffect } from 'react'
import { View, Image,Button } from '@tarojs/components'
import {  AtButton, AtInput  } from "taro-ui"
import Taro from '@tarojs/taro'
import api from '../../http/api'


import './index.less'
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/button.scss";

export default (props: any) => {
  useEffect(()=>{
    // console.log()
  },[])
  const [tel,setTel] = useState('')
  const [code,setCode] = useState('')
  const [time,setTime] = useState(60)
  const [showTime,setShowTime] = useState(false)
  const onChange1 = (e) => {
    setTel(e)
  }
  const onChange2 = (e) => {
    setCode(e)
  }
  const onSubmit = (e:any) => {
    console.log(props.tid)
    const url = props.tid.split('url=')[1].split('&')[0]
    if(tel&&code){
        Taro.getUserInfo({
          success: function(res) {
            if(res.userInfo){
              // 获取到用户信息验证码正确
              api.login({
                tel:tel,
                code:code,
                nickName:res.userInfo.nickName,
                avatarUrl:res.userInfo.avatarUrl
              }).then((res:any)=>{
                Taro.setStorage({
                  key:'info',
                  data:JSON.stringify(res.data)
                })
                Taro.reLaunch({
                  url:url
                })
              })
            }else{
              Taro.showToast({
                title: '请先授权',
                icon: 'none'
              })
            }
          }
        })
    }else{
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
    }
  }
  const getCode = ()=>{
    setShowTime(true)
    api.sendMsg({
      tel:tel
    })
    let n = 60
    const timer = setInterval(()=>{
      n--
      if(n===0){
        clearInterval(timer)
        setShowTime(false)
      }
      setTime(n)
    },1000)
  }
  const getUserInfo=(e)=>{
  }
  return (
    <View className='login'>
      <Image className='bg' src={IMGSRC+'bgLogin.png'}></Image>
      <View className='loginForm'>
      <View className='at-icon at-icon-user ico ico1'></View>
      <View className='at-icon at-icon-lock ico ico2'></View>
      
      {
        showTime?(<View className='time code'>{time}s</View>):(<View className='code' onClick={getCode}>获取验证码</View>)
      }
      
        <AtInput
        className='input'
        name='tel'
        type='number'
        placeholder='请输入手机号'
        value={tel}
        onChange={onChange1}
      > </AtInput>
     
      <AtInput
      className='input'
        name='code'
        type='number'
        placeholder='请输入验证码'
        value={code}
        onChange={onChange2}
      />
      <Button onClick={onSubmit} open-type='getUserInfo' onGetUserInfo={getUserInfo} className='submit'  type='primary' >登录/注册</Button>
    </View>
    </View>
  )
}
